package xgenerator.ui.swing.adapter;

import java.awt.Component;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

import xgenerator.service.MetadataService;
import xgenerator.service.impl.MetadataServiceImpl;
import xgenerator.ui.swing.JGeneratorFrame;
import xgenerator.ui.swing.MetadataTable;
import xgenerator.ui.swing.model.MetadataTableModel;
import xgenerator.util.StringUtils;

public class TableColumnComboBoxPopupMenuListener implements PopupMenuListener {

	/**
	 * MetadataService
	 */
	private MetadataService metadataService;
	
	/**
	 * UI组件
	 */
	private Component ui;
	
	/**
	 * constructor
	 * @param ui
	 */
	public TableColumnComboBoxPopupMenuListener(Component ui) {
		this.ui = ui;
		this.metadataService = new MetadataServiceImpl();
	}
	
	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 * @see javax.swing.event.PopupMenuListener#popupMenuCanceled(javax.swing.event.PopupMenuEvent)
	 */
	public void popupMenuCanceled(PopupMenuEvent e) {

	}

	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 * @see javax.swing.event.PopupMenuListener#popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent)
	 */
	public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
		
	}

	/**
	 * <p>
	 * Title：
	 * </p>
	 * @author <a href="mailto:shushanlee@msn.com">liss</a>
	 * @param e
	 * @see javax.swing.event.PopupMenuListener#popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent)
	 */
	public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
		MetadataTable metadataTable = (MetadataTable) ui;
		JGeneratorFrame jGeneratorFrame = (JGeneratorFrame) metadataTable.getParentComponent();
		JComboBox datasourceComboBox = jGeneratorFrame.getDataSourceComboBox();
		Object selectedItem = datasourceComboBox.getSelectedItem();
		String datasourceName = StringUtils.toString(selectedItem);
		System.out.println("datasourceName=" + datasourceName);
		
		int selectedRowIndex = metadataTable.getSelectedRow();
		System.out.println("selectedRowIndex=" + selectedRowIndex);
		Object selectedTableCellValue = metadataTable.getValueAt(selectedRowIndex, MetadataTableModel.REFERENCING_TABLE_INDEX);
		String referencingTableName = StringUtils.toString(selectedTableCellValue);
		System.out.println("referencingTableName=" + referencingTableName);

		Vector dataVector = metadataService.getTableColumns(datasourceName, referencingTableName);
		JComboBox comboBox = (JComboBox) e.getSource();
		comboBox.setModel(new DefaultComboBoxModel(dataVector));
	}

}
